﻿namespace Example.Creational.Multiton
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;

    public sealed class Rolodex
    {
        private static readonly Rolodex _rolodex = new Rolodex();

        private Rolodex()
        {
            Cards = new Collection<Card>();
        }

        private Collection<Card> Cards { get; set; }

        public static Card Open(string key)
        {
            Card result;

            lock (_rolodex)
            {
                result = _rolodex.Cards
                    .Where(x => string.Equals(x.Key, key, StringComparison.Ordinal))
                    .FirstOrDefault();

                if (null == result)
                {
                    result = new Card(key);
                    _rolodex.Cards.Add(result);
                }
            }

            return result;
        }
    }
}